import React, { memo, Component } from 'react'
import { Image, Table, Button, Input, Select, message, Modal } from 'antd'
import './index.css'
import { baseUrl } from '../../assets/baseUrl'
import { StudentInfo } from '../../utils/model'
import {
  queryPrizeList,
  getClasslist,
  queryAwardSelection,
  deletePresetAward,
  putNewPresetAward,
  queryVerifyList
} from '@/api/index'
import { formatDate, getDateDiff, exportExcel } from '../../utils/tool'
import TemplateTwo from '../home/component/EmailTemplate/template_two'
import { levelEnums, RangeEnums } from '../../utils/enums'

import * as echarts from 'echarts'

const BaseUrl = baseUrl()
const { Option } = Select

class PrizeBackStage extends Component {
  static contextType = StudentInfo
  constructor(props) {
    super(props)
    this.state = {
      pageSize: 10,
      pageNum: 1,
      total: 10,
      totalList: [], //全部获奖情况
      tableList: [], //表格数据
      classId: null, //筛选项---班级
      year: null, //筛选项---年
      month: null, //筛选项---月
      level: null, //筛选项---获奖等级 国家，省，学校，班级
      prizeLevel: null, //筛选项---奖项等级 一等奖 二等奖 三等奖...
      classList: [], //班级列表
      preSetList: [], //预设奖项列表
      chooseSetLevel: '', //奖项预设值所选level
      newPresetName: '', //新增预设奖项名
      addPresetVisible: false, //新增预设弹窗可见
      verifyList: [], //待审核列表
      verifyModalVisible: false //审核弹窗
    }
  }
  componentDidMount() {
    if (!this.context?.studentInfo?.schoollevel?.split(',').includes('100')) {
      message.error('无权限！')
    } else {
      queryPrizeList({}).then((res) => {
        this.setState(
          {
            totalList: res.data.data,
            tableList: res.data.data
          },
          () => {
            this.painTotalChart()
            this.painPrizeLevelChart()
            
            this.getPresetList()
          }
        )
      })
      getClasslist({ schoolId: this.context?.studentInfo?.schoolId }).then(
        (res) => {
          this.setState({
            classList: res.data.data
          })
        }
      )
      
      this.getVerifyTable()
    }
  }

  getVerifyTable = () => {
    queryVerifyList().then((res) => {
      this.setState({
        verifyList: res.data.data
      })
    })
  }
  reflashTable = (method = 'query') => {
    const { classId, year, month, level, prizeLevel } = this.state
    if (!this.context?.studentInfo?.schoolLevel?.split(',').includes('100')) {
      message.error('无权限！')
    } else {
      if (method == 'download') {
        exportExcel(
          '/prize/queryPrizeList',
          { classId, year, month, level, prizeLevel, method },
          '获奖情况导出'
        )
      } else
        queryPrizeList({
          classId,
          year,
          month,
          level,
          prizeLevel,
          method
        }).then((res) => {
          // if(method == 'download'){
          //   let blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
          // let url = window.URL.createObjectURL(blob);
          // // window.location.href = url;  //本窗口打开直接下载

          // // 重命名   创建a标签
          // var a = document.createElement('a');
          // // 下载a 标签中 href 指向的文件，根据 download 中设定的值，对文件进行重命名。
          // a.href = url
          // // 设置文件名，不写默认原文件名称
          // a.download = '新文件名'
          // a.click()
          // }
          this.setState({
            tableList: res.data.data
          })
        })
    }
  }

  /* 获取预设奖项列表 */
  getPresetList = () => {
    queryAwardSelection().then((res) => {
      this.setState({
        preSetList: res.data.data
      },()=>{
        this.painAllTotalChart()
      })
    })
  }


  painTotalChart = () => {
    let { totalList } = this.state
    let myChart = echarts.init(document.getElementById('total'))
    const option = {
      title: {
        text: '奖项类别统计',
        subtext: '(已通过审核)',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: ['国家级', '省级', '校级', '其他']
      },
      series: [
        {
          name: '奖项类别',
          type: 'pie',
          radius: '55%',
          center: ['40%', '50%'],
          data: [
            {
              name: '国家级',
              value: totalList.filter((i) => i.level == 0).length
            },
            {
              name: '省级',
              value: totalList.filter((i) => i.level == 1).length
            },
            {
              name: '校级',
              value: totalList.filter((i) => i.level == 2).length
            },
            {
              name: '其他',
              value: totalList.filter((i) => i.level == 3).length
            }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    myChart.setOption(option)
  }
  painPrizeLevelChart = () => {
    let { totalList } = this.state
    let myChart = echarts.init(document.getElementById('prizeLevel'))
    const option = {
      title: {
        text: '奖项等次统计',
        subtext: '(已通过审核)',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: [
          '一等奖',
          '二等奖',
          '三等奖',
          '金牌',
          '银牌',
          '无等级划分',
          '其他'
        ]
      },
      series: [
        {
          name: '奖项类别',
          type: 'pie',
          radius: '55%',
          color: [
            '#ee6666',
            '#73c0de',
            '#5470c6',
            '#fc8452',
            '#9a60b4',
            '#91cc75',
            '#fac858',
            '#3ba272',
            '#ea7ccc'
          ],
          center: ['40%', '50%'],
          data: [
            {
              name: '一等奖',
              value: totalList.filter((i) => i.prizeLevel == 0).length
            },
            {
              name: '二等奖',
              value: totalList.filter((i) => i.prizeLevel == 1).length
            },
            {
              name: '三等奖',
              value: totalList.filter((i) => i.prizeLevel == 2).length
            },
            {
              name: '金牌',
              value: totalList.filter((i) => i.prizeLevel == 3).length
            },
            {
              name: '银牌',
              value: totalList.filter((i) => i.prizeLevel == 4).length
            },
            {
              name: '无等级划分',
              value: totalList.filter((i) => i.prizeLevel == 5).length
            },
            {
              name: '其他',
              value: totalList.filter((i) => i.prizeLevel == 6).length
            }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    myChart.setOption(option)
  }

  painAllTotalChart = () =>{
      let { totalList, preSetList } = this.state
      preSetList.map(item=>{
        let count = totalList.filter(i=>(i.name == item.name)).length
        item.count = count
      })
      preSetList = preSetList.sort((a,b)=>{return b.count-a.count})
      let myChart = echarts.init(document.getElementById('allTotal'))
      const option = {
        xAxis: {
          type: 'category',
          data: preSetList?.map((i,index)=>(index+1))
        },
        yAxis: {
          type: 'value'
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            let row = preSetList[Number(params.name-1)]
            return `${levelEnums.find((i) => (i.key == row.level)).value}<br/>${row.name}<br/>总获奖数量：${row.count}`
          }
        },
        series: [
          {
            data: preSetList?.map((i)=>(i.count)),
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      };
      myChart.setOption(option)
    
  }
  /* 删除预设奖项 */
  deletePreSet = () => {
    const { chooseLevelPrizeKey, preSetList } = this.state
    if (
      preSetList.find((i) => (i.prizeKey === chooseLevelPrizeKey).length === 0)
    ) {
      message.error('该奖项不存在哦~')
      return
    }
    Modal.confirm({
      content: '确认删除此项奖项？',
      okText: '删除',
      onOk: () => {
        deletePresetAward({
          prizeKey: chooseLevelPrizeKey
        }).then((res) => {
          if (res.data.success) message.success(res.data.message)
          this.getPresetList()
        })
      }
    })
  }

  /* 新增预设奖项 */
  addPreset = () => {
    const { newPresetName, chooseSetLevel } = this.state
    if (chooseSetLevel === '') {
      message.error('请选择奖项类别！')
      return
    }
    if (newPresetName === '') {
      message.error('请输入奖项名称！')
      return
    }
    putNewPresetAward({ name: newPresetName, level: chooseSetLevel }).then(
      (res) => {
        if (res.data.success) {
          message.success(res.data.message)
          this.setState(
            {
              addPresetVisible: false
            },
            () => this.getPresetList()
          )
        }
      }
    )
  }
  render() {
    const {
      tableList,
      classList,
      preSetList,
      chooseSetLevel,
      newPresetName,
      addPresetVisible,
      verifyList,
      verifyModalVisible,
      verifyLineKey
    } = this.state

    let columns = [
      {
        title: '奖项分类',
        dataIndex: 'level',
        align: 'center',
        render: (item) => {
          return levelEnums.find((i) => i.key == item)?.value
        }
      },
      ,
      {
        title: '获奖年份',
        dataIndex: 'year',
        align: 'center',
        width: 100,
        render: (i) => i + '年'
      },
      {
        title: '获奖月份',
        dataIndex: 'month',
        align: 'center',
        width: 100,
        render: (i) => i + '月'
      },
      {
        title: '奖项名称',
        dataIndex: 'name',
        align: 'center',
        width: 200
        // render:(item,row)=>{
        //   return <TextFlow text={item} clamp={1} width={150}></TextFlow>
        // }
      },
      {
        title: '姓名',
        dataIndex: 'realName',
        align: 'center',
        width: 100
      },
      {
        title: '班级',
        dataIndex: 'className',
        align: 'center',
        width: 200
      },
      {
        title: '获奖等级',
        dataIndex: 'prizeLevel',
        align: 'center',
        render: (item) => {
          return RangeEnums.find((i) => i.key == item)?.value
        }
      },{
        title: '是否队长',
        dataIndex: 'captain',
        align: 'center',
        render: (item) => {
          return item == 1 ? '是' :'否'
        }
      },
      {
        title: '作品名称',
        dataIndex: 'workName',
        align: 'center',
      },
      {
        title: '指导教师',
        dataIndex: 'teachers',
        align: 'center',
      }
      // {
      //   title: '操作',
      //   align: 'center',
      //   render: () => {
      //     return <span style={{ cursor: 'pointer', color: 'red' }}>删除</span>
      //   }
      // }
    ]

    const verifyColumns = [
      {
        title: '班级',
        dataIndex: 'className',
        align: 'center',
        width: 200
      },
      {
        title: '姓名',
        dataIndex: 'realName',
        align: 'center',
        width: 100
      },
      {
        title: '奖项分类',
        dataIndex: 'level',
        align: 'center',
        render: (item) => {
          return levelEnums.find((i) => i.key == item).value
        }
      },
      {
        title: '奖项名称',
        dataIndex: 'name',
        align: 'center',
        width: 200
      },
      {
        title: '获奖等级',
        dataIndex: 'prizeLevel',
        align: 'center',
        render: (item) => {
          return RangeEnums.find((i) => i.key == item).value
        }
      },
      {
        title: '上传时间',
        dataIndex: 'createTime',
        align: 'center',
        render: (item) => {
          return formatDate(item) + '(' + getDateDiff(item) + ')'
        }
      },
      {
        title: '班管通过时间',
        dataIndex: 'allowTime',
        align: 'center',
        render: (item) => {
          return formatDate(item) + '(' + getDateDiff(item) + ')'
        }
      },
      {
        title: '操作',
        align: 'center',
        render: (item, row) => {
          return (
            <span
              style={{ cursor: 'pointer', color: '#00b1ff' }}
              onClick={() => {
                this.setState({
                  verifyModalVisible: true,
                  verifyLineKey: row.lineKey
                })
              }}
            >
              去审核
            </span>
          )
        }
      }
    ]
    // //分页器
    // const pagination = {
    //   pageNum: this.state.pageSize,
    //   pageSize: this.state.pageSize,
    //   onChange: (e) => {
    //     this.setState(
    //       {
    //         pageNum: e
    //       },
    //       () => {
    //         this.getList()
    //       }
    //     )
    //   },
    //   total: this.state.total
    // }
    return (
      <div className="setting-opration">
        <div
          style={{
            width: '100%',
            height: '100%',
            overflowY: 'auto',
            padding: '36px 24px',
            background: 'rgba(255,255,255,.8)'
          }}
        >
          <div className="charts">
            <div className="chart" id="total"></div>
            <div className="chart" id="prizeLevel"></div>
          </div>
          <div style={{ padding: '6px 2vw' }}>
            <div style={{ display: 'flex', flexWrap: 'wrap' }}>
              <div style={{ marginRight: 24, marginTop: 24 }}>
                奖项分类：
                <Select
                  defaultValue="全部"
                  style={{ width: 120 }}
                  onChange={(e) => {
                    this.setState(
                      {
                        level: e
                      },
                      () => this.reflashTable()
                    )
                  }}
                >
                  <Option value="">全部</Option>

                  {levelEnums.map((item) => {
                    return <Option value={item.key}>{item.value}</Option>
                  })}
                </Select>
              </div>
              <div style={{ marginRight: 24, marginTop: 24 }}>
                年份：
                <Select
                  defaultValue="全部"
                  style={{ width: 120 }}
                  onChange={(e) => {
                    this.setState(
                      {
                        year: e
                      },
                      () => this.reflashTable()
                    )
                  }}
                >
                  <Option value="">全部</Option>
                  <Option value={2022}>2022年</Option>
                  <Option value={2021}>2021年</Option>
                  <Option value={2020}>2020年</Option>
                  <Option value={2019}>2019年</Option>
                  <Option value={2018}>2018年</Option>
                </Select>
              </div>
              <div style={{ marginRight: 24, marginTop: 24 }}>
                月份：
                <Select
                  defaultValue="全部"
                  style={{ width: 120 }}
                  onChange={(e) => {
                    this.setState(
                      {
                        month: e
                      },
                      () => this.reflashTable()
                    )
                  }}
                >
                  <Option value="">全部</Option>
                  {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((i) => {
                    return <Option value={i}>{i + '月'}</Option>
                  })}
                </Select>
              </div>
              <div style={{ marginRight: 24, marginTop: 24 }}>
                班级：
                <Select
                  defaultValue="全部"
                  style={{ width: 240 }}
                  onChange={(e) => {
                    this.setState(
                      {
                        classId: e
                      },
                      () => this.reflashTable()
                    )
                  }}
                >
                  <Option value="">全部</Option>
                  {classList.map((i) => {
                    return <Option value={i.classId}>{i.className}</Option>
                  })}
                </Select>
              </div>
              <div style={{ marginRight: 24, marginTop: 24 }}>
                获奖等级：
                <Select
                  defaultValue="全部"
                  style={{ width: 120 }}
                  onChange={(e) => {
                    this.setState(
                      {
                        prizeLevel: e
                      },
                      () => this.reflashTable()
                    )
                  }}
                >
                  <Option value="">全部</Option>
                  {RangeEnums.map((i) => {
                    return <Option value={i.key}>{i.value}</Option>
                  })}
                </Select>
              </div>
              <div style={{ marginRight: 24, marginTop: 24 }}>
                <Button
                  onClick={this.reflashTable.bind(this, 'download')}
                  type="primary"
                >
                  导出excel
                </Button>
              </div>
            </div>
            <div style={{ marginTop: 12 }}>
              <Table
                columns={columns}
                dataSource={tableList}
                // onChange={this.changeTable.bind(this)}
                // locale={{
                //   cancelSort: '点击取消排序',
                //   triggerAsc: '点击升序',
                //   triggerDesc: '点击降序'
                // }}
                // pagination={pagination}
              />
            </div>
          </div>
          <div
            className="charts"
            style={{ height: 700, marginBottom: 24, padding: 24 }}
          >
            <div style={{ height: 652, flex: 1 }} id="allTotal"></div>
          </div>
          <div className="charts" style={{ maxHeight: 300 }}>
            <h1 style={{ fontSize: 24, fontWeight: 550, paddingLeft: 24 }}>
              奖项预设值管理
            </h1>
            <div style={{ padding: '0 20%' }}>
              <div
                style={{
                  marginRight: 24,
                  marginTop: 24,
                  fontSize: 16,
                  fontWeight: 550
                }}
              >
                <div style={{ paddingTop: 18 }}>
                  奖项分类：
                  <Select
                    defaultValue="全部"
                    style={{ width: 120 }}
                    onChange={(e) => {
                      this.setState({
                        chooseSetLevel: e
                      })
                    }}
                  >
                    <Option value="">全部</Option>
                    {levelEnums.map((item) => {
                      return <Option value={item.key}>{item.value}</Option>
                    })}
                  </Select>
                </div>
                <div style={{ marginTop: 18 }}>
                  对应奖项：
                  <Select
                    style={{ width: 280 }}
                    onChange={(e) => {
                      this.setState({
                        chooseLevelPrizeKey: e
                      })
                    }}
                  >
                    {chooseSetLevel === ''
                      ? preSetList.map((item) => {
                          return (
                            <Option value={item.prizeKey}>{item.name}</Option>
                          )
                        })
                      : preSetList
                          .filter((i) => i.level === chooseSetLevel)
                          .map((item) => {
                            return (
                              <Option value={item.prizeKey}>{item.name}</Option>
                            )
                          })}
                  </Select>
                </div>
                <div style={{ marginTop: 24 }}>
                  <Button
                    type="danger"
                    style={{ marginRight: 18 }}
                    onClick={this.deletePreSet.bind(this)}
                  >
                    删除所选奖项
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => this.setState({ addPresetVisible: true })}
                  >
                    新增奖项
                  </Button>
                  <Modal
                    visible={addPresetVisible}
                    title="新增奖项"
                    onCancel={() => {
                      this.setState({ addPresetVisible: false })
                    }}
                    footer={[
                      <Button
                        key="submit"
                        type="primary"
                        onClick={this.addPreset.bind(this)}
                      >
                        新增
                      </Button>
                    ]}
                  >
                    <div>
                      <div>
                        当前选中奖项分类：
                        {levelEnums.find((i) => i.key === chooseSetLevel)
                          ?.value || '未选择'}
                      </div>
                      <div style={{ display: 'flex', marginTop: 24 }}>
                        <span style={{ minWidth: 120, textAlign: 'right' }}>
                          奖项名：
                        </span>
                        <Input
                          value={newPresetName}
                          allowClear
                          onChange={(e) => {
                            this.setState({ newPresetName: e.target.value })
                          }}
                          placeholder="请输入新增预设奖项名称"
                          width={160}
                        ></Input>
                      </div>
                    </div>
                  </Modal>
                </div>
              </div>
            </div>
          </div>
          <h1
            style={{
              fontSize: 24,
              fontWeight: 550,
              paddingLeft: 24,
              marginTop: 24
            }}
          >
            待审核列表
          </h1>

          <div className="charts" style={{ marginTop: 24 }}>
            <div style={{margin:'auto'}}>
              <Table columns={verifyColumns} dataSource={verifyList} />
            </div>
            <Modal
              visible={verifyModalVisible}
              title="审核奖项"
              onCancel={() => {
                this.setState({ verifyModalVisible: false })
              }}
              width={650}
              footer={null}
            >
              <div style={{ minWidth: 600, width: 600 }}>
                <TemplateTwo extra={verifyLineKey}></TemplateTwo>
              </div>
            </Modal>
          </div>
        </div>
      </div>
    )
  }
}
export default memo(PrizeBackStage)
